<template>
  <PageWrapper v-loading="loadingRef" contentFullHeight fixedHeight dense>
    <AdVxeTable @register="registerTable">
      <template #tools>
        <Authority :value="'Root.Admin.Identity.Role.Create'">
          <a-button type="primary" @click="handleCreate">
            <Icon icon="ant-design:plus-circle-outlined" />{{
              t('routes.system.identity.role.addRole')
            }}
          </a-button>
        </Authority>
      </template>
      <template #actionCol="{ row }">
        <TableAction
          outside
          :actions="[
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: t('common.delText'),
              auth: 'Root.Admin.Identity.Role.Delete', // 权限控制
              ifShow: (_action) => {
                return row?.Deletable === true && row?.IsSystem !== true; // 根据业务控制是否显示: 是否可删除的数据权限状态
              },
              popConfirm: {
                title: t('common.delConfirmText'),
                placement: 'left',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
          :dropDownActions="[
            {
              icon: 'clarity:note-edit-line',
              label: t('common.editText'),
              auth: 'Root.Admin.Identity.Role.Update', // 权限控制
              ifShow: (_action) => {
                return row?.Updatable === true; // 根据业务控制是否显示: 是否可更新的数据权限状态
              },
              onClick: handleEdit.bind(null, row),
            },
            {
              icon: 'la:user-cog',
              label: t('routes.system.identity.user.title'),
              auth: ['Root.Admin.Identity.User.ReadRoleUsers'], // 权限控制
              onClick: handleSetUsersModalOpen.bind(null, row),
            },
            {
              icon: 'clarity:organization-line',
              label: t('routes.system.identity.organization.title'),
              auth: 'Root.Admin.Identity.Organization.ReadRoleOrganizations', // 权限控制
              onClick: handleSetOrganizationsModalOpen.bind(null, row),
            },
            {
              icon: 'ant-design:safety-certificate-outlined',
              label: t('routes.system.identity.permissionText'),
              auth: 'Root.Admin.Identity.Role.SetModules', // 权限控制
              onClick: handleModuleDrawerOpen.bind(null, row),
            },
            {
              icon: 'ant-design:security-scan-outlined',
              label: t('routes.system.identity.viewFunctionText'),
              auth: 'Root.Admin.Auth.RoleFunction.ReadFunctions', // 权限控制
              onClick: handleReadFunctions.bind(null, row),
            },
          ]"
        />
      </template>
    </AdVxeTable>

    <RoleUserModal
      @register="registerSetUsersModal"
      :title="t('routes.system.identity.role.title')"
      :search="true"
      :closeFunc="handleSetUsersModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.Role.SetUsers'"
      :okFunc="handleSetUsersModalOk"
      width="50%"
    />
    <TreeDrawer
      @register="registerModuleDrawer"
      :title="t('routes.system.identity.permissionText')"
      :toolbar="true"
      :search="true"
      :checkable="true"
      :closeFunc="handleModuleDrawerClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.Role.SetModules'"
      :okFunc="handleModuleDrawerOk"
      width="70%"
    />
    <RoleFunctionDrawer
      @register="registerDrawer"
      :title="t('routes.system.identity.role.roleFunctions')"
    />
    <RoleOrganizationTransferModal
      @register="registerSetOrganizationsModal"
      :title="t('routes.system.identity.organization.title')"
      :search="true"
      :closeFunc="handleSetOrganizationsModalClose"
      :okText="t('common.updateText')"
      :okAuthority="true"
      :okAuthorityCode="'Root.Admin.Identity.Role.SetOrganizations'"
      :okFunc="handleSetOrganizationsModalOk"
      width="50%"
    />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Authority } from '@/components/Authority';
  import { useI18n } from '@/hooks/web/useI18n';
  import { PageWrapper } from '@/components/Page';
  import { useMessage } from '@/hooks/web/useMessage';

  import { AdVxeTable, useAdVxeTable, TableAction } from '@/components/AdVxeTable';
  import {
    readRoles,
    createRoles,
    updateRoles,
    deleteRoles,
    setRoleUsers,
    setRoleOrganizations,
    setRoleModules,
  } from '@/api/identity/admin/role';
  import { readRoleUsers } from '@/api/identity/admin/user';
  import { readRoleOrganizations } from '@/api/identity/admin/organization';
  import { readRoleModules } from '@/api/authorization/admin/module';
  import { FormModeEnum } from '@/enums/formEnum';

  import Icon from '@/components/Icon/Icon.vue';

  import { useModal } from '@/components/AdVxeModal';
  import { TreeItem, TreeActionType } from '@/components/Tree';

  import { TreeDrawer } from '@/components/ViewModal';

  import { useDrawer } from '@/components/Drawer';
  import RoleFunctionDrawer from './RoleFunctionDrawer.vue';

  import { columns, makeRoleModulesTree } from './role.data';

  import UserTransferModal from '../user/UserTransferModal.vue';
  import OrganizationTransferModal from '@/views/system/identity/organization/OrganizationTransferModal.vue';

  const RoleUserModal = UserTransferModal;
  const RoleOrganizationTransferModal = OrganizationTransferModal;

  defineOptions({ name: 'RolePage' });

  const { t } = useI18n();
  const { createMessage } = useMessage();

  const loadingRef = ref(false);

  const [registerTable, { openDetailForm, reload }] = useAdVxeTable({
    id: 'system-role-page-table',
    // 表标题呈现器
    title: t('routes.system.identity.role.roleList'),
    // 表格数据接口请求对象
    api: readRoles,
    // 详情表单
    detailForm: {
      // 表单标识
      formIndex: 'identity_role_detail',
      // 主键字段
      keyField: 'Id',
      // 详情表单抬头
      title: t('routes.system.identity.role.title'),
      // 实体新增接口请求对象
      createApi: createRoles,
      // 实体更新接口请求对象
      updateApi: updateRoles,
    },
    // 表单列信息 AdColumn[]
    columns,
    // 使用搜索表单
    searchForm: true,
    // 是否带有边框 boolean | default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    border: false,
    // 是否显示序号列
    showSeqColumn: true,
    // 排序配置项 multiple-多字段排序 chronological-按点击先后顺序排序
    sortConfig: { multiple: true, chronological: true },
    // 表格右侧操作列配置 AdColumn
    actionColumn: {
      width: 80,
      title: t('common.actionText'),
      fixed: 'right',
      slots: { default: 'actionCol' },
    },
  });

  /** 处理创建角色 */
  async function handleCreate() {
    openDetailForm(FormModeEnum.Add);
  }
  /** 处理编辑角色 */
  async function handleEdit(record: any) {
    openDetailForm(FormModeEnum.Edit, record);
  }
  /** 处理删除角色 */
  async function handleDelete(record: any) {
    // console.log(record);
    const result = await deleteRoles([record.Id]);
    if (result.Succeeded) {
      createMessage.success(t('common.successText'));
      reload();
    }
  }

  //#region "设置角色用户"
  const [registerSetUsersModal, setUsersModalMethods] = useModal();
  /** 处理打开设置账户角色弹窗 */
  async function handleSetUsersModalOpen(record: any) {
    if (record && record.Id) {
      const userNodes = await readRoleUsers(record.Id);

      setUsersModalMethods.openModal(true, {
        userNodes: userNodes,
        record: record,
      });
      setUsersModalMethods.setModalProps({
        title: `${t('routes.system.identity.role.title')} - ${record.Name}`,
      });
    }
  }
  /** 处理设置账户角色弹窗关闭按钮 */
  async function handleSetUsersModalClose() {
    return true;
  }
  /** 处理设置账户角色弹窗确定按钮 */
  async function handleSetUsersModalOk(
    targetKeys: (string | bigint)[],
    roleNodes: any[],
    record: any,
  ) {
    if (targetKeys && roleNodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const userIds = checkedKeys;
        const result = await setRoleUsers({ RoleId: record.Id, UserIds: [...userIds] });
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          reload();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion

  const [registerModuleDrawer, moduleDrawerMethods] = useDrawer();
  /** 处理打开设置权限抽屉 */
  async function handleModuleDrawerOpen(record: any) {
    if (record && record.Id) {
      loadingRef.value = true;
      try {
        const roleModules = await readRoleModules(record.Id);
        let treeItems: TreeItem[] = [];
        let checkedKeys: (string | bigint)[] = [];
        treeItems = makeRoleModulesTree(roleModules, checkedKeys);
        // console.log(checkedKeys);
        moduleDrawerMethods.openDrawer(true, {
          treeData: treeItems,
          checkedKeys: checkedKeys,
          record: record,
        });
        moduleDrawerMethods.setDrawerProps({
          title: `${t('routes.system.identity.permissionText')} - ${record.Name}`,
        });
      } finally {
        loadingRef.value = false;
      }
    }
  }
  /** 处理设置权限抽屉关闭按钮 */
  async function handleModuleDrawerClose() {
    return true;
  }
  /** 处理设置权限抽屉确定按钮 */
  async function handleModuleDrawerOk(record: any, treeRef: TreeActionType | null) {
    if (treeRef && record && record.Id) {
      const checkedKeys = treeRef.getCheckedKeys();
      if (checkedKeys) {
        // console.log(checkedKeys);
        const moduleIds = checkedKeys as unknown as (string | bigint)[];
        const result = await setRoleModules({
          RoleId: record.Id,
          ModuleIds: [...moduleIds],
        });
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          reload();
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }

  const [registerDrawer, { openDrawer, setDrawerProps }] = useDrawer();
  /** 处理读取用户功能 */
  async function handleReadFunctions(record: any) {
    openDrawer(true, {
      roleId: record.Id,
    });
    setDrawerProps({
      title: `${t('routes.system.identity.role.roleFunctions')} - ${record.Name}`,
    });
  }

  //#region "设置组织"
  const [registerSetOrganizationsModal, setOrganizationsModalMethods] = useModal();
  /** 处理打开设置组织机构弹窗 */
  async function handleSetOrganizationsModalOpen(record: any) {
    const orgNodes = await readRoleOrganizations(record.Id);
    // console.log('handleSetOrganizationsModalOpen', orgNodes);
    setOrganizationsModalMethods.openModal(true, {
      organizationNodes: orgNodes,
      record: record,
    });
    setOrganizationsModalMethods.setModalProps({
      title: `${t('routes.system.identity.organization.title')} - ${record.Name}`,
    });
  }
  /** 处理设置组织机构弹窗关闭按钮 */
  async function handleSetOrganizationsModalClose() {
    return true;
  }
  /** 处理设置组织机构弹窗确定按钮 */
  async function handleSetOrganizationsModalOk(
    targetKeys: (string | bigint)[],
    nodes: any[],
    record: any,
  ) {
    if (targetKeys && nodes && record && record.Id) {
      const checkedKeys = targetKeys;
      if (checkedKeys) {
        // console.log(checkedKeys);
        const roleOrganizations: any[] = [];
        checkedKeys.forEach((item) => {
          roleOrganizations.push({
            OrganizationId: item,
            Administrator: false,
            Leader: false,
          });
        });
        const result = await setRoleOrganizations({
          RoleId: record.Id as string,
          RoleOrganizations: [...roleOrganizations],
        });
        if (result.Succeeded) {
          createMessage.success(t('common.successText'));
          return true;
        } else {
          return false;
        }
      }
      return true;
    } else {
      return true;
    }
  }
  //#endregion
</script>
